<?php


namespace app\api\controller;

use app\common\model\Help;
use think\Controller;
use think\Request;
use think\facade\Cache;
use think\Db;
class Permission extends Controller
{
    /**
     * 获取用户权限列表
     * @return \think\response\Json
     */
    public function getUserPermissions()
    {
        try {
            $userId = input("userId")??'10000';

            if (!$userId) {
                return json([
                    'code' => 400,
                    'message' => '未登录',
                    'data' => []
                ]);
            }

            // 尝试从缓存获取权限
            $cacheKey = 'user_permissions:' . $userId;
            $permissions = Cache::get($cacheKey);

            $cacheKey2 = 'user_menu:' . $userId;
            $menu_list = Cache::get($cacheKey2);

            if (!$permissions){
                $arr = $this->getPermissionsByUserId($userId);
                if($arr){
                    $permissions = $arr['permissions']??[];
                    $menu_list = $arr['menu_list']??[];

                    //缓存1小时
                    Cache::set($cacheKey, $permissions, 3600);
                    Cache::set($cacheKey2, $menu_list, 3600);
                }
            }

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $permissions,
                'menu'=> $menu_list
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取权限失败：' . $e->getMessage(),
                'data' => [],
                'menu'=> []
            ]);
        }
    }

    /**
     * 根据用户ID获取权限
     * @param int $userId
     * @return array
     */
    private function getPermissionsByUserId($userId=10000)
    {
        // 查询用户角色
        $system_user = Db::table('system_user')
            ->where('id', $userId)
            ->find();

        $role_key = $system_user['role'];
        $p_id = $system_user['p_id'];

        if (empty($role_key)) {
            return ['permissions'=>[],'menu_list'=>[]];
        }

        // 查询角色对应的权限菜单
        $role_id = Db::table('system_role')
            ->where(["role_key"=>$role_key])->where(['system_user_id'=>$p_id])
            ->value('id');

        if (empty($role_id)) {
            return ['permissions'=>[],'menu_list'=>[]];
        }
        // 查询菜单权限信息
        if($role_id!=2){
            $menus = Db::table('system_role_menus')
                ->where('role_id', 'in', $role_id)
                ->field('id, role_id, menu_id')
                ->column('menu_id');
        }else{
            $menus = Db::table('system_role_menus')
                ->where('role_id', 'in', $role_id)->where(['system_user_id'=>$userId])
                ->field('id, role_id, menu_id')
                ->column('menu_id');
        }

        $result = array_filter($menus, 'is_numeric');

        $permissions = Db::table('system_menus')->field("id name,permission code")->where("id","in",$result)->select();
        $menu_list = Db::table('system_menus')->field("id name,link_url code")->where("type='menu'")->where("id","in",$result)->select();

        if($permissions){
            return ['permissions'=>$permissions,'menu_list'=>$menu_list];
        }else{
            return ['permissions'=>[],'menu_list'=>[]];
        }
    }

    /**
     * 获取当前用户ID（根据你的认证系统调整）
     * @return int
     */
    private function getUserId()
    {
        // 模拟数据 - 实际使用时删除
        return 10000;
    }


    //刷新权限
    public function reload_permission(){
        $help = new Help();
        $user = $help->system_user_find();
        $userId = input("userId")??'';

        Cache::clear();
        $array = $this->getPermissionsByUserId($userId);

        if(($user['role']=='superAdmin')&&($user['p_id']==10000)){
            $system_business = Db::table("system_business")->field("system_code")->select();
            $arr = [];
            foreach ($system_business as $k =>&$v){
                array_push($arr,$v['system_code']);
                $menus_arr = Db::table("system_menus")->field("id")->where(['business'=>$v['system_code']])->column("id");
                foreach ($menus_arr as $k2 =>&$v2){
                    array_push($arr,$v2);
                }
            }
            Db::table("system_role_menus")->where(['role_id'=>1])->delete();
            $time = date('Y-m-d H:i:s');
            foreach ($arr as $k =>&$v){
                $d['role_id'] = 1;
                $d['menu_id'] = $v;
                $d['create_time'] = $time;
                Db::table("system_role_menus")->insert($d);
            }

            $userId = $user['id'];
            if($array){
                $permissions = $array['permissions']??[];
                $menu_list = $array['menu_list']??[];

                // 缓存1小时
                $cacheKey = 'user_permissions:' . $userId;
                Cache::set($cacheKey, $permissions, 3600);

                $cacheKey2 = 'user_menu:' . $userId;
                Cache::set($cacheKey2, $menu_list, 3600);
            }

        }else{
            if($userId){
                if($array){
                    $permissions = $array['permissions']??[];
                    $menu_list = $array['menu_list']??[];

                    // 缓存1小时
                    $cacheKey = 'user_permissions:' . $userId;
                    Cache::set($cacheKey, $permissions, 3600);

                    $cacheKey2 = 'user_menu:' . $userId;
                    Cache::set($cacheKey2, $menu_list, 3600);
                }
            }
        }

        $result = ['code' => 200, 'message' => '请求成功', 'data' => [], 'success' => true];
        echo json_encode($result);
    }

}